package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    RedisTemplate redisTemplate;

    private Map map = new HashMap();

    //用于添加菜品
    @PostMapping
    @CacheEvict(value = "dish",key = "#dishDto.categoryId+':'+#dishDto.status")
    public R save(@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());
        dishService.saveDish(dishDto);
        return R.success("保存成功!");
    }

    //用于分页查询菜品
    @GetMapping("/page")
    public R pageQuery(int page, int pageSize, String name) {

        //先把基础查出来
        IPage<Dish> pg = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);
        dishService.page(pg, qw);
        long total = pg.getTotal();//总条数
        List<Dish> records = pg.getRecords();// 查询列表数据

        map.clear();

        // records: List<Dish>
        // 只有菜品分类id：categoryId，没有分类名称
        // 根据菜品分类id，查询菜品分类数据。在set进去

        // 拉姆达表达式的写法： List<Dish> records ---> List<DishDto> dishDtos
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        map.put("total", total);
        map.put("records", dishDtos);
        return R.success(map);
    }

    //用于获得单例信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.reGetById(id);
        return R.success(dishDto);
    }

    //用于修改信息
    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R update(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    //用于删除数据
    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R deleteDish(@RequestParam List<Long> ids) {

        System.out.println(ids);
        // TODO 完成业务逻辑
        dishService.removeByIds(ids);

        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        //TODO update dish set status = 前端给我啥就是啥，错了找前端
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Dish::getId, id).set(Dish::getStatus, status);
            dishService.update(null, updateWrapper);
        }
        return R.success("操作成功");
    }

    //用于根据条件查询对应的菜品数据
    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#dish.categoryId+':'+#dish.status")
    public R<List<DishDto>> select(Dish dish) {
        List<DishDto> collect = null;
        //使用缓存
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        collect = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //当redis有直接返回,没有再查询数据库
        if (collect != null) {
            return R.success(collect);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        collect = list.stream().map((one) -> {
            DishDto dishDto = new DishDto();
            //1.把dish的属性值copy给dishDto
            BeanUtils.copyProperties(one, dishDto);
            //2.查询菜品的口味数据
            // select * from dish_flavor where dish_id = ?
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId, one.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            //3.将菜品的口味列表 set给 dishDto
            dishDto.setFlavors(flavors);
            //4.将dishDto放入到 dishDtos 集合中
            return dishDto;
        }).collect(Collectors.toList());

        //redis中没有,添加到redis中
        redisTemplate.opsForValue().set(key, collect, 60l, TimeUnit.MINUTES);

        return R.success(collect);
    }
}
